<template>
  <div class="app-container">
    <TheQueryForm :option="searchOption" @onSubmit="onSubmit" @onClear="onClear"></TheQueryForm>
    <el-row style="margin-bottom: 20px">
      <el-col :span="18">
        <el-radio-group size="small" v-model="queryParams.payState">
          <el-radio-button label>全部</el-radio-button>
          <el-radio-button label="COMPLETED">已完成</el-radio-button>
          <el-radio-button label="PENDING_PAYMENT">
            待付款
            <el-badge :value="count" v-if="count>0" :max="99" class="badge"></el-badge>
          </el-radio-button>
          <el-radio-button label="APPROVAL_PENDING">审批中</el-radio-button>
          <el-radio-button label="APPROVAL_REJECTED">审批拒绝</el-radio-button>
        </el-radio-group>
      </el-col>
      <el-col :span="6" style="display: flex; justify-content: flex-end">
        <el-button type="success" size="small" @click="handleCreate">保证金收款规则</el-button>
        <el-button type="primary" size="small" @click="handleReturn">新增退款</el-button>
        <el-button size="small" :loading="exportLoading" @click="handleExport">导出Excel</el-button>
      </el-col>
    </el-row>
    <TheTable
      ref="tableRefs"
      :tableOption="tableOption"
      :pageNo.sync="pageNo"
      :limit.sync="limit"
      :api="queryPageApi"
      :queryParams="queryParams"
      :renderFunc="renderFunc"
      :autoPlay="false"
    />
    <ReturnRecord ref="returnRecordRefs" @onRevocation="onRevocation" />
    <BailRule ref="bailRuleRefs" />
    <Return ref="returnRefs" @refresh="onRefresh" />
    <TheDingAuth ref="dingAuthRefs" />
  </div>
</template>
<script>
import BailRule from "./components/bailRule.vue";
import Return from "./components/return.vue";
import ReturnRecord from "./components/returnRecord.vue";
import TheDingAuth from "@/components/TheDingAuth/index.vue";
import {
  apiWorkerSecurityDepositRecordPage,
  apiWorkerSecurityDepositRecordExport,
  apiWorkerSecurityDepositRecordCount,
  apiWorkerSecurityDepositRevocation
} from "@/api/bail.js";
export default {
  components: { ReturnRecord, BailRule, Return, TheDingAuth },
  data() {
    const _this = this;
    return {
      count: 0,
      queryPageApi: apiWorkerSecurityDepositRecordPage,
      queryParams: { payState: "" },
      pageNo: 1,
      limit: 10,
      exportLoading: false,
      searchOption: [
        {
          field: "workerMobile",
          label: "师傅手机号",
          placeholder: "师傅手机号",
          maxlength: 11,
          rules: [],
          type: "Input",
          defaultValue: ""
        },

        {
          type: "Select",
          field: "type",
          label: "类型",
          placeholder: "类型",
          required: false,
          rules: [],
          options: [
            { label: "收款", value: "INCREASE" },
            { label: "退款", value: "DECREASE" }
          ],
          defaultValue: ""
        },
        {
          type: "DatePickerRange",
          field: "time",
          label: "发起时间",
          placeholder: "发起时间",
          required: false,
          rules: []
        }
      ],
      tableOption: [
        {
          label: "保证金流水id",
          prop: "id",
          width: 80
        },
        {
          label: "类型",
          prop: "type",
          width: 80,
          formatter({ type }) {
            return type == "INCREASE" ? "收款" : "退款";
          }
        },
        {
          label: "金额",
          prop: "changeAmount",
          width: 120,
          formatter({ changeAmount }) {
            return this.$filters.filterPriceFormat(changeAmount);
          }
        },
        {
          label: "师傅信息",
          prop: "user",
          width: 200,
          render(createElement, { row }) {
            const dom = (
              <div class="">
                <div>{row.workerId}</div>
                <div>{row.workerName}</div>
                <div>{row.userPhoneNumber}</div>
              </div>
            );
            return dom;
          }
        },
        {
          label: "状态",
          prop: "status",
          width: 60,
          formatter({ payState, type }) {
            if (type == "INCREASE") {
              // 收款
              return payState == "PENDING_PAYMENT"
                ? "待付款"
                : payState == "COMPLETED"
                ? "已完成"
                : "--";
            } else {
              // 退款
              return payState == "APPROVAL_PENDING"
                ? "审核中"
                : payState == "APPROVAL_FINISH"
                ? "已完成"
                : payState == "APPROVAL_REJECTED"
                ? "审批拒绝"
                : "--";
            }
          }
        },
        {
          label: "发起时间",
          width: 120,
          prop: "createTime",
          render(createElement, { row }) {
            try {
              const strArr = row.createTime.split(" ");
              const dom = (
                <div class="row">
                  <div>{strArr[0]}</div>
                  <div>{strArr[1]}</div>
                </div>
              );
              return dom;
            } catch (error) {
              return <div></div>;
            }
          }
        },

        {
          label: "完成时间",
          width: 100,
          prop: "updateTime",
          render(createElement, { row }) {
            try {
              const strArr = row.updateTime.split(" ");
              const dom = (
                <div>
                  <div>{strArr[0]}</div>
                  <div>{strArr[1]}</div>
                </div>
              );
              return dom;
            } catch (error) {
              return <div></div>;
            }
          }
        },

        {
          label: "操作",
          width: 120,
          prop: "operate",
          fixed: "right",
          render(h, { row }) {
            return h("el-row", [
              // 退款显示
              h("el-link", {
                domProps: {
                  innerHTML: "查看详情"
                },
                props: {
                  type: "primary"
                },
                directives: [
                  {
                    name: "column-domItem-show",
                    value: ["DECREASE"].includes(row.type) //非待处理阶段显示
                  }
                ],
                on: {
                  click() {
                    _this.$refs.returnRecordRefs.open({
                      id: row.id,
                      businessType: "WORKER_SECURITY_DEPOSIT_REFUND"
                    });
                  }
                }
              }),

              h("el-link", {
                domProps: {
                  innerHTML: "撤回"
                },
                class: ["ml20"],
                props: {
                  type: "warning"
                },
                directives: [
                  {
                    name: "column-domItem-show",
                    value:
                      ["DECREASE"].includes(row.type) &&
                      row.payState == "APPROVAL_PENDING" //非待处理阶段显示
                  }
                ],
                on: {
                  click() {
                    _this
                      .$prompt("此操作将撤销退款申请, 是否继续?", "提示", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        inputPlaceholder: "撤回原因..."
                      })
                      .then(({ value }) => {
                        _this.$refs.dingAuthRefs.open(result => {
                          const params = {
                            id: row.id,
                            dingtalkUserId: result.initiateDingtalkId
                          };
                          apiWorkerSecurityDepositRevocation(params).then(
                            res => {
                              if (res.code == "SUCCESS") {
                                _this.$message({
                                  type: "success",
                                  message: res.msg
                                });
                                _this.$refs.tableRefs.refresh();
                              } else {
                                _this.$message({
                                  type: "error",
                                  message: res.msg
                                });
                              }
                            }
                          );
                        });
                      })
                      .catch(() => {});
                  }
                }
              })
            ]);
          }
        }
      ]
    };
  },
  mounted() {},
  methods: {
    onRevocation() {
      this.$refs.tableRefs.refresh();
    },
    renderFunc(res) {
      apiWorkerSecurityDepositRecordCount({ payState: "PENDING_PAYMENT" }).then(
        res => {
          this.count = res.data;
        }
      );
      return res;
    },
    handleCreate() {
      this.$refs.bailRuleRefs.open();
    },
    onRefresh() {
      this.$refs.tableRefs.refresh();
    },
    handleReturn() {
      this.$refs.returnRefs.open();
    },
    // 导出
    async handleExport() {
      this.exportLoading = true;
      const res = await apiWorkerSecurityDepositRecordExport({
        ...this.queryParams
      });
      if (res.code === "SUCCESS") {
        let header = [
          {
            title: "保证金流水id",
            prop: "id",
            valueType: "s"
          },
          {
            title: "类型",
            prop: "type",
            valueType: "s"
          },
          {
            title: "金额",
            prop: "changeAmount",
            valueType: "n",
            numFmt: $numFmt.money
          },
          {
            title: "师傅信息",
            prop: "",
            children: [
              {
                title: "师傅id",
                prop: "workerId",
                valueType: "s"
              },
              {
                title: "师傅姓名",
                prop: "workerName",
                valueType: "s"
              },
              {
                title: "师傅手机号",
                prop: "userPhoneNumber",
                valueType: "s"
              }
            ]
          },
          {
            title: "状态",
            prop: "payState",
            valueType: "s"
          },
          {
            title: "发起时间",
            prop: "createTime",
            valueType: "s"
          },
          {
            title: "完成时间",
            prop: "updateTime",
            valueType: "s"
          }
        ];

        let dataSource = res.data.map(item => {
          return {
            ...item,
            status: "",
            changeAmount: item.changeAmount / 100,
            type: item.type == "increase" ? "收款" : "退款",
            payState:
              item.type == "increase"
                ? "PENDING_PAYMENT"
                  ? "待付款"
                  : item.payState == "COMPLETED"
                  ? "已完成"
                  : "--"
                : item.payState == "APPROVAL_PENDING"
                ? "审核中"
                : item.payState == "APPROVAL_FINISH"
                ? "已完成"
                : item.payState == "APPROVAL_REJECTED"
                ? "审批拒绝"
                : "--"
          };
        });
        const option = {
          dataSource: dataSource,
          header: header,
          fileName: "保证金管理"
        };
        window.$Json2Excel(option);
        this.exportLoading = false;
      } else {
        this.$message({
          message: "导出操作失败,请重试",
          type: "warring"
        });
        this.exportLoading = false;
      }
    },

    onSubmit({ values }) {
      if (values.hasOwnProperty("time")) {
        values = {
          ...values,
          startTime: values.time ? values.time[0] : "",
          endTime: values.time ? values.time[1] : ""
        };
        delete values.time;
      }
      this.queryParams = { ...this.queryParams, ...values };
    },
    onClear() {
      this.queryParams = { payState: "" };
    }
  }
};
</script>
<style scoped lang="scss">
::v-deep .row {
  display: flex;
  .span4 {
    flex: 1;
  }
  .span20 {
    flex: 5;
  }
}
.badge {
  position: absolute;
  right: -0px;
  top: -10px;
  transform: scale(0.9);
}
</style>
